#!/usr/bin/env python

import os, sys
import healpy as hp
import numpy as np
from argparse import ArgumentParser
from cosat.gif import *
from PIL import Image, ImageDraw
import imageio
import matplotlib.pylab as plt

def getFitsList(band='', nside=512, idx_yrTags='yrTags.txt'):
    flist = []
    yrs = []

    print('type(band) = {}'.format(type(band)))

    if band in ['NUV','u','g','r','i','z','y']:
        basename = band + '_' + 'NSIDE_' + str(nside)
        print('--> basename: {}'.format(basename))
    else:
        basename = 'NSIDE_' + str(nside)

    tmp = np.loadtxt(idx_yrTags)
    for i in range(tmp.shape[0]):
        yrs.append(tmp[i,1])
        flist.append(basename+'_'+str(i+1)+'.fits')

    return basename, flist, yrs

def makePNG(band=None, nside=512, idx_yrTags='yrTags.txt', min=None, max=None, norm='log', unit=None, coord='E', cmap=True, cbar=None):
    basename, flist, yrs = getFitsList(band=band, nside=nside, idx_yrTags=idx_yrTags)
    
    if band == '':
        titlebase = 'All_bands'
    else:
        titlebase = band
    
    plist = []
    for i in range(len(flist)):
        if os.path.isfile(flist[i]):
            print('found: {}'.format(flist[i]))

        m = hp.read_map(flist[i])
        title = titlebase + '_YEAR: ' + str( round(yrs[i],1) )

        hp.mollview( m, min=min, \
                        max=max, \
                        norm=norm, \
                        unit=unit, \
                        coord=coord, \
                        cmap=cmap, \
                        cbar=cbar,
                        title=title )

        hp.graticule()
        pngName = titlebase+'_'+str(i+1)+'.png'
        plt.savefig(pngName, format='png')
        plist.append(pngName)
        print('> exported: {}'.format(pngName))

    return plist

def makeGIF(plist, gifName, duration=1000.0):
    print('plist: {}'.format(plist))
    print('gifName: {}'.format(gifName))
    print('duration: {}'.format(duration))
    imlist = []
    for i in range(len(plist)):
        imlist.append(Image.open(plist[i]))
    imageio.mimsave(gifName, imlist, duration=duration)